import sys, pygame, game
from scenes import *

class Menu(object):
    def __init__(self, screen):
        pygame.init()
        self.screen = screen
        self.keepGoing = True
        self.root = True
        self.menu = None

        self.root_menu()
        self.main_loop()
       
    def new_game(self):
        game.Game(self.screen) 
        
    def get_saved_lvl(self):
        i = self.count_levels()
        while i > 0:
            if os.path.exists(filepath("..\saves\lvl%d.sav" % i)):
                return i
            i -= 1
        return 0
    
    def get_lvl_score(self, lvl):
        try:
            return int(open(filepath("..\saves\lvl%d.sav" % lvl)).read())
        except:
            return 0
        
    def levels(self):
        #i = 1
        #options = open("gamelib\empty.txt")
        #while i <= self.count_levels():
        #    levelStr = "Level %d" % i
        #    scoreStr = "(Highscore %d)" % self.get_lvl_score(i)
        #    options = (["%(level)s %(score)s" % { 'level':levelStr, 'score':scoreStr}, lambda: self.play_level(i)])
        #    options = ([levelStr, lambda: self.play_level(i)])
        #    i += 1
        #options = ([""])
        #options = (["Back", lambda: self.root_menu()])
        
        self.menu = MenuStyle(
            ["Level 1 (Highscore %d)" % self.get_lvl_score(1), lambda: self.play_level(1)],
            ["Level 2 (Highscore %d)" % self.get_lvl_score(2), lambda: self.play_level(2)],
            ["Level 3 (Highscore %d)" % self.get_lvl_score(3), lambda: self.play_level(3)],
            ["Back", lambda: self.root_menu()])
        
        self.set_menu(self.menu, False)
       
    def root_menu(self):
        self.menu = MenuStyle(
            ["New Game", lambda: self.new_game()],
            ["Help", lambda: self.help(self.screen)],
            ["Select Level", lambda: self.levels()],
            ["Quit Game", lambda: self.quit()])
        self.set_menu(self.menu, True)
        
    def set_menu(self, menu, bool):
        self.root = bool
        menu.center_at(320, 240)
        menu.set_font(pygame.font.Font(filepath("fonts/font2.ttf"), 64))
        menu.set_highlight_color((0, 255, 0))
        menu.set_normal_color((255, 255, 255))
        
    def play_level(self, lvl):
        unlocklvl = self.get_saved_lvl() + 1
        if lvl <= unlocklvl:
            game.Game(self.screen, lvl)
        else:
            self.menu.set_highlight_color((255, 0, 0))
        
    def help(self, screen):
        cutscene(screen, ["HELP",
        "",
        "Move: Arrow Keys",
        "Shoot: Spacebar",
        "Return: Back to Menu",
        "Note: Don't get hit!",
        ""])
    
    def quit(self):
        sys.exit()
        
    def count_levels(self):
        i = 1
        while os.path.exists(filepath("level%d.png" % i)) == True:
            i += 1
        return i - 1
        
    def main_loop(self):
        while self.keepGoing:
    
            self.events = pygame.event.get()
    
            self.menu.update(self.events)
    
            for e in self.events:
                if e.type == pygame.QUIT:
                    quit()   
                elif e.type == pygame.KEYDOWN:
                    if e.key == pygame.K_ESCAPE:
                        if self.root:
                            self.keepGoing = False
                        else:
                            self.root_menu()
    
            self.screen.fill((0, 0, 0))
            self.menu.draw(self.screen)
            pygame.display.flip()
            
class MenuStyle:

    def __init__(self, *options):
        self.options = options
        self.x = 0
        self.y = 0
        self.font = pygame.font.Font(None, 32)
        self.option = 0
        self.width = 1
        self.color = [0, 0, 0]
        self.hcolor = [255, 0, 0]
        self.height = len(self.options)*self.font.get_height()
        for o in self.options:
            text = o[0]
            ren = self.font.render(text, 1, (0, 0, 0))
            if ren.get_width() > self.width:
                self.width = ren.get_width()

    def draw(self, surface):
        i = 0
        for o in self.options:
            if i == self.option:
                clr = self.hcolor
            else:
                clr = self.color
            text = o[0]
            ren = self.font.render(text, 1, clr)
            if ren.get_width() > self.width:
                self.width = ren.get_width()
            surface.blit(ren, (400 - ren.get_width()/2, (240 - self.font.get_height()*3/2 + i*self.font.get_height())))
            i += 1
            
    def update(self, events):
        for e in events:
            if e.type == pygame.KEYDOWN:
                if e.key == pygame.K_DOWN:
                    self.option += 1
                if e.key == pygame.K_UP:
                    self.option -= 1
                if e.key == pygame.K_RETURN:
                    self.options[self.option][1]()
        if self.option > len(self.options)-1:
            self.option = 0
        if self.option < 0:
            self.option = len(self.options)-1

    def set_pos(self, x, y):
        self.x = x
        self.y = y
        
    def set_font(self, font):
        self.font = font
        
    def set_highlight_color(self, color):
        self.hcolor = color
        
    def set_normal_color(self, color):
        self.color = color
        
    def center_at(self, x, y):
        self.x = x-(self.width/2)
        self.y = y-(self.height/2)
        
    def add_option(self, option):
        self.options.append(option)
        
        for o in self.options:
            text = o[0]
            ren = self.font.render(text, 1, (0, 0, 0))
            if ren.get_width() > self.width:
                self.width = ren.get_width()
